(function () {

  // 判断 affix-menu 位置
  function buildAffixMenu() {
    var affixMenu = ['<ul id="matters-scrollspy" class="matters-affix-menu affix-menu">'];
    $('.matters-content .matters-subtitle').each(function () {
      var $this = $(this)
      affixMenu.push('<li class="affix-menu-item"><a href="#' + $this.attr('id') + '">' + $this.text() + '</a></li>')
    })
    affixMenu.push('</ul>')
    affixMenu = affixMenu.join('')

    $('.matters-affix-menu').remove()
    $('.matters-content').append(affixMenu)

    // affix
    var $mattersAffixMenu = $('.matters-affix-menu')
    $mattersAffixMenu.affix({
      offset: {
        top: function () {
          var offsetTop = $mattersAffixMenu.offset().top
          var sideBarMargin = parseInt($mattersAffixMenu.children(0).css('margin-top'), 10)
          var navOuterHeight = $('.header').height()

          return (this.top = offsetTop - navOuterHeight - sideBarMargin)
        },
        bottom: function () {
          return (this.bottom = $('.footer').outerHeight(true) + 80)
        }
      }
    })

    // scrollspy
    $('body').scrollspy({
      target: '#matters-scrollspy',
      offset: 90
    })
  }
  buildAffixMenu()

  // affix-menu 锚点跳转
  $(document).on('click.affix-menu', '.affix-menu-item a, .matters-toolbox-materials', function (e) {
    var $this = $(this)
    var $target = $($this.attr('href'))

    if ($target.length > 0) {
      $('html, body').animate({
        scrollTop: $target.offset().top - 60
      }, 600)
    }

    return false
  })

  // 小屏吸顶不一样
  // true 是大屏  || false 是小屏
  function isMoreThenMd() {
    // 加上 scroll 宽度
    return window.SCREEN_SIZE > 2
  }

  // matters-affix button
  function affixInit() {
    var $mattersAffix = $('.matters-affix')
    var $mattersAffixBtn = $mattersAffix.find('.matters-toolbox-btn-affix')
    var affixHeight = $mattersAffix.height()
    $mattersAffixBtn.affix({
      offset: {
        top: function () {
          // 小屏才实现
          if (!isMoreThenMd()) {
            var offsetTop = $mattersAffix.offset().top
            var sideBarMargin = parseInt($mattersAffix.children(0).css('margin-top'), 10)
            return (offsetTop + affixHeight - sideBarMargin)
          } else {
            return 10000
          }
        }
      }
    })

    // 触发页面滚动事件 解决 affix 元素未初始化问题
    $(document).trigger('scroll')
  }
  setTimeout(affixInit, 100)
  $(window).on('resize.affix-matters', function () {
    $(document).trigger('scroll')
  })


  function mattersAffix() {
    var $mattersAffix = $('.matters-aside-affix')

    function handleNormalDom(activeDelete) {
      // 判断是否已经注入元素
      var top = $mattersAffix.css('top')
      if (top === 'auto') top = 0
      var needDom = parseInt(top, 10) > 0
      var $prependDom = $mattersAffix.find('.matters-aside-box[data-affix-append="true"]')
      if (needDom && !$prependDom.length) {
        var $leftBtn = $('.matters-affix .matters-toolbox-btn-affix').clone()
        $leftBtn.removeClass('matters-toolbox-apply matters-toolbox-btn-affix affix-top')
        $leftBtn.addClass('btn btn-primary')
        $leftBtn.css('width', '15rem')
        $leftBtn.css('max-width', '100%')
        var $div = $('<div></div>')
        $div.addClass('matters-aside-box')
        $div.attr('data-affix-append', true)
        $div.attr('align', 'center')
        $div.append($leftBtn)
        $mattersAffix.prepend($div)
      } else if (activeDelete || !needDom && $prependDom.length) {
        $prependDom.remove()
      }
    }

    $mattersAffix.affix({
      offset: {
        top: function () {
          var $prevDom = $mattersAffix.prev('.matters-aside')
          if ($mattersAffix.hasClass('affix')) {
            $mattersAffix.width($prevDom.width())
          } else {
            $mattersAffix.width('unset')
          }
          var offsetY = $prevDom.offset().top + $prevDom.outerHeight()
          if (isMoreThenMd()) {
            handleNormalDom()
            return offsetY + 20
          } else {

            // 移动端不吸顶
            handleNormalDom(true)
            return 10000
          }
        },
        bottom: function () {
          return ($('.footer').outerHeight(true) + 130)
        }
      }
    })

    // 触发页面滚动事件 解决 affix 元素未初始化问题
    $(document).trigger('scroll')
  }
  setTimeout(mattersAffix, 100)

  // 收藏办事指南
  // $(document).on('click', '.matters-favourite', function() {
  //   var $this = $(this)
  //   var isFavourited = $this.hasClass('favourited')
  //   if (isFavourited) {
  //     $this.removeClass('favourited').html('收藏指南')
  //   } else {
  //     $this.addClass('favourited').html('已收藏')
  //   }
  // })

  // 基本信息折叠
  $(document).on('click', '.matters-table-fold-toggle', function () {
    var $this = $(this)
    var $fold = $this.closest('.matters-table-fold')
    if ($fold.hasClass('unfold')) {
      $fold.removeClass('unfold')
      $this.text('显示更多')
    } else {
      $fold.addClass('unfold')
      $this.text('收起')
    }
  })

  // 文字折叠
  $('.matters-truncate').each(function () {
    var $this = $(this)
    if ($this.height() > 110) {
      $this.append('<a class="matters-truncate-toggle" href="javascript:;"><span class="matters-truncate-expand">展开 <i class="icon icon-down"></i></span><span class="matters-truncate-unexpand">收起 <i class="icon icon-up"></i></span></a>')
      $this.append('<p class="matters-truncate-fixed-toggle container"><span>收起<i class="icon icon-up"></i></span></p>')
      var dotOpts = {
        ellipsis: '...',
        height: 110,
        keep: '.matters-truncate-toggle',
        truncate: 'letter'
      }
      $this.dotdotdot(dotOpts)
    }
  })


  var truncateToggleOffsetTop = 120

  $(document).on('click', '.matters-truncate-fixed-toggle', function () {
    var $truncate = $(this).closest('.matters-truncate')
    var instance = $truncate.data('dotdotdot')
    instance.truncate()
    window.scrollTo(0, $truncate.offset().top - truncateToggleOffsetTop)
  })

  $(document).on('click', '.matters-truncate-toggle', function (e) {
    var $this = $(this)
    var $truncate = $this.closest('.matters-truncate')
    var instance = $truncate.data('dotdotdot')

    function dddScrollHandle() {
      var scrollTop = $(document).scrollTop()
      var offsetTop = $truncate.offset().top
      var $mattersTruncateFixedToggle = $truncate.find('.matters-truncate-fixed-toggle')
      var pageCurrentTop = $(window).height() + scrollTop
      var currentTop = offsetTop + $truncate.height()
      if ((offsetTop - truncateToggleOffsetTop) < scrollTop) {
        $mattersTruncateFixedToggle.show()
        if (pageCurrentTop > currentTop) {
          $mattersTruncateFixedToggle.hide()
        } else {
          $mattersTruncateFixedToggle.show()
        }
      } else {
        $mattersTruncateFixedToggle.hide()
      }
    }
    setTimeout(dddScrollHandle, 100)

    var padding = false

    function dddScrollRemove() {
      var self = this

      if (!padding) {
        padding = true
        setTimeout(function () {
          padding = false
          dddScrollHandle()
        }, 100)
      }
    }

    if ($truncate.hasClass('ddd-truncated')) {
      $(document).on('scroll', dddScrollRemove)
      instance.restore()
    } else {
      $(document).off('scroll', dddScrollRemove)
      if ($(window).height() < $truncate.height()) {
        window.scrollTo(0, $truncate.offset().top - truncateToggleOffsetTop)
      }
      instance.truncate()
    }




  })

  // 办事指南反馈
  var $feedbackHelper = $('.feedback-helper')
  var $feedbackAction = $('.feedback-helper-action-area')
  var feedbackSuccessTpl = '<span class="feedback-helper-action-result">感谢反馈 <i class="icon icon-selected"></i></span>'
  var feedbackFormTpl = '<div class="feedback-helper-action-form">' +
    '<textarea class="feedback-helper-action-textarea form-textarea" placeholder="您的意见是我们改进的动力"></textarea>' +
    '<a class="feedback-helper-action-submit btn btn-default btn-small">提交</a>' +
    '<a class="feedback-helper-action-cancel btn btn-link btn-small">取消</a>' +
    '</div>'
  $(document)
    .on('click', '.feedback-helper-action-agree', function () {
      // 点击有帮助
      var feedbackData = $feedbackHelper.data()
      feedbackData.helpful = 1
      feedbackData.url = window.location.href

      typeof TA !== 'undefined' && TA.send('feedback.matter', feedbackData)

      $feedbackAction.html(feedbackSuccessTpl)
    })

    .on('click', '.feedback-helper-action-deny', function () {
      // 点击没有帮助显示反馈表单
      $feedbackAction.html(feedbackFormTpl)
    })

    .on('click', '.feedback-helper-action-submit', function () {
      // 提交反馈
      var feedbackData = $feedbackHelper.data()
      feedbackData.helpful = 0
      feedbackData.url = window.location.href
      feedbackData.content = $('.feedback-helper-action-textarea').val()

      typeof TA !== 'undefined' && TA.send('feedback.matter', feedbackData)

      $feedbackAction.html(feedbackSuccessTpl)
    })

    .on('click', '.feedback-helper-action-cancel', function () {
      // 取消提交反馈
      $feedbackAction.html('<a href="javascript:;" class="btn btn-default btn-small feedback-helper-action-agree">是</a><a href="javascript:;" class="btn btn-default btn-small feedback-helper-action-deny">否</a>')
    })


  var videoPlayer = null

  function buildVideoModal(videoUrl) {
    var $modal = $('#modalMatterVideo')
    if ($modal.length > 0) {
      $modal.find('.video-js source').attr('src', videoUrl)
    } else {
      $modal = $('<div id="modalMatterVideo" class="modal fade">' +
        '<div class="modal-dialog">' +
        '<div class="modal-hd"><a href="javascript:;" class="modal-close" data-dismiss="modal"></a></div>' +
        '<div class="modal-bd">' +
        '<video id="modalMatterVideoPlayer" class="video-js vjs-16-9" controls autoplay preload="auto"><source src="' + videoUrl + '" type="video/mp4"></video>' +
        '</div>' +
        '</div>' +
        '</div>')
      $('body').append($modal)
    }

    setTimeout(function () {
      $modal.modal('show')
      videoPlayer = videojs('modalMatterVideoPlayer')
      videoPlayer && videoPlayer.play()
    }, 100)
  }

  $(document).on('hide.bs.modal', '#modalMatterVideo', function () {
    videoPlayer && videoPlayer.pause()
  })

  // 点击查看视频
  $(document).on('click', '.matters-aside-video', function () {
    var $this = $(this)
    var videoUrl = $this.data('video')
    buildVideoModal(videoUrl)
  })
})()
